#pragma once

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
#include"Protocol.hpp"



const std::string Seq = "\r\n";
bool Encode(std::string &message) // 添加报头
{
    if (message.empty())
    {
        return false;
    }
    std::string pack = std::to_string(message.size()) + Seq + message + Seq;
    message = pack;
    return true;
}
//  len+\r\n+message+\r\n
bool Decode(std::string &message, std::string *out) // 去除报头
{
    if (message.empty())
        return false;
    auto pos = message.find(Seq);
    if (pos == std::string::npos)
        return false;
    int len = stoi(message.substr(0, pos));
    if (len + Seq.size() * 2 + pos < message.size())
    {
        return false;
    }
    *out = message.substr(pos + Seq.size(), len);
    message.erase(0, len + Seq.size() * 2 + pos);
    return true;
}
class Calculator
{
public:
    Calculator()
    {}
    Response Execute( Request &request)
    {
        Response response;
        switch (request.Op())
        {
        case '+':
      response.SetResult(request.X() + request.Y());
      response.SetErrorCode(0);
      break;
        case '-':
        response.SetResult(request.X() - request.Y());
        response.SetErrorCode(0);
        break;
        case '*':
        response.SetResult(request.X() * request.Y());
        response.SetErrorCode(0);
        break;
        case '/':
        if (request.Y() == 0)
        {
            response.SetErrorCode(1); // division by zero
            response.SetResult(0);
        }
        else
        {
            response.SetResult(request.X() / request.Y());
            response.SetErrorCode(0);
        }
        break;
        default:
        response.SetErrorCode(2); // unsupported operation
        response.SetResult(0);
        break;
        }
        return response;
    }
    ~Calculator() {}
};